With Ternary
The &&
operator allows us to conditionally render something if a condition is met. But what if we want to render something else if the condition isn't met?
For example, suppose we're building an admin dashboard. If the user is logged in, we want to render the charts and tables and everything. If they're not logged in, we want to render a short message asking them to log in.
We could use two &&
operators, like this:
function App({ user }) { const isLoggedIn = !!user;
return ( <> {isLoggedIn && <AdminDashboard />} {!isLoggedIn && <p>Please login first</p>} </> );}
This works, but it's a bit clunky. Fortunately, we can use the ternary operator to help us out.
Here's what it looks like:
function App({ user }) { const isLoggedIn = !!user;
return ( <> {isLoggedIn ? <AdminDashboard /> : <p>Please login first</p>} </> );}
The ternary operator isn't new; it's been a part of the JavaScript language since Internet Explorer 3 launched in 1996! But for a long time, it was a pretty obscure language feature.
It's particularly useful in a React context because it allows us to embed if/else logic within our JSX. Because the ternary operator is an operator instead of a statement, it can be used inside JavaScript expressions.
A ternary operator consists of three parts:
condition ? firstExpression : secondExpression
If condition
is truthy, the first expression will be the one that gets evaluated. If it's falsy, the second expression will be evaluated instead.